package shop.servlet;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import shop.DAO.OffersDAO;
import shop.bean.OfferBean;
import shop.bean.UserBean;

public class AdminServlet extends HttpServlet{


	public void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, java.io.IOException {

		HttpSession session = request.getSession();	 
		//logged in ?
		if (session.getAttribute("currentUser") == null) {
			response.sendRedirect("login");
			return;
		}

		//do admin stuff
		if(((UserBean) session.getAttribute("currentUser")).getRole() != null){
			//increase stocks

			Map<String, String[]> toAdd = request.getParameterMap();
			for ( Iterator<Entry<String, String[]>> iter = toAdd.entrySet().iterator(); iter.hasNext(); ) {
				Entry<String, String[]> entry = iter.next();
				try{
					int productId = Integer.parseInt(entry.getKey());
					int quantity = Integer.parseInt(entry.getValue()[0]);

					OfferBean o = OffersDAO.getOffer(productId);
					if(o != null){
						o.setQuantity(quantity + o.getQuantity());
						OffersDAO.saveOffer(o);
					}
				}
				catch (Throwable theException){}
			}

			

			//Add new products
			if(request.getParameter("name") != null 
					&& request.getParameter("region") != null
					&& request.getParameter("description") != null
					&& request.getParameter("price") != null
					&& request.getParameter("country") != null
			){
				try{
					OfferBean o = new OfferBean();
					o.setQuantity(0);
					o.setName((String) request.getParameter("name"));
					o.setRegion((String) request.getParameter("region"));
					o.setCountry(Integer.parseInt((String) request.getParameter("country")));
					o.setPrice(Integer.parseInt((String) request.getParameter("price")));
					o.setDescription((String) request.getParameter("description"));
					
					OffersDAO.newOffer(o);
				}
				catch (Throwable theException){System.out.println(theException);}
			}


			doGet(request, response);
		}
	}
	
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, java.io.IOException {

		HttpSession session = request.getSession();	    
		if (session.getAttribute("currentUser") == null) {
			response.sendRedirect("login");
		}
		else{
			//displays admin form
			Collection<OfferBean> offers = OffersDAO.getOffers();
			request.setAttribute("offers", offers); 
			RequestDispatcher rd = request.getRequestDispatcher("admin.jsp"); 
			rd.forward(request,response);	
		}
	}
}
